﻿using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
 
namespace Kernelx.Contexts.Repositories
{
    using Core;
    using System;

    internal class ModelibOfWork<TDbContext> : IModelibOfWork
        where TDbContext : DbContext
    {

        private readonly bool _isMaster;
        private TDbContext _dbContext;

        public ModelibOfWork(TDbContext dbContext)
        {
            _dbContext = dbContext;
            _isMaster = true;
        }

        internal ModelibOfWork(TDbContext dbContext,bool isMaster)
        {
            _dbContext = dbContext;
            _isMaster = isMaster;
        }

        public bool IsTransactioning => _dbContext.Database.CurrentTransaction != null;

        public ITransaction BeginTransaction() => new Transaction(_dbContext.Database.BeginTransaction());


        private Dictionary<string, object> _stores = new();
        public IModelStore<T> Store<T>(string targetName = null) where T : class, new()
        {
            IModelStore<T> result = null;
            var key = targetName ?? typeof(T).Name;

            if (!_stores.ContainsKey(key))
            {
                lock (_stores)
                    if (!_stores.ContainsKey(key))
                        _stores.Add(key, result = new ModelStore<T>(_dbContext.Set<T>(targetName)));
            }
            return result ?? _stores[key] as IModelStore<T>;
        }

        public void Dispose()
        {
            _stores?.Clear();
            _stores = null;
            _dbContext=null;
        }

        public int SaveChanges()
        {
            if(_isMaster)
                return _dbContext.SaveChanges();
            throw new NotSupportedException("从库的接口实例不支持此操作");
        }

        public Task<int> SaveChangesAsync(CancellationToken token = default)
        {
            if (_isMaster) 
                return _dbContext.SaveChangesAsync(token);
            throw new NotSupportedException("从库的接口实例不支持此操作");          
        }
    }
}
